In this article we will discuss different ways to iterate over a set in C++.
Let’s create a set of strings i.e.
1
2
3
4
5
6
7
// Set of strings
std::set<std::string> setOfStr = {
"jjj",
"khj",
"bca",
"aaa",
"ddd" };
Now let’s iterate over it and print the contents on screen using different methods i.e.
Iterating over a Set using Iterators
set::begin() returns an iterator pointing to the first element in set. Whereas, set::end() returns an iterator past the end of set.
Now to iterate a set in forward direction, we need to create an iterator and initialise it with set::begin(). So that it points to start of set and then we will keep on access and increment the iterator to next till set::end() is reached i.e.
1
2
3
4
5
6
7
8
9
10
11
// Creating a iterator pointing to start of set
std::set<std::string>::iterator it = setOfStr.begin();
// Iterate till the end of set
while (it != setOfStr.end())
{
// Print the element
std::cout << (*it) << ",";
//Increment the iterator
it++;
}
Here we iterated the set in forward direction. Now, let’s see how to iterate in reverse direction.
Iterating a set in backward direction using reverse_iterator
set::rbegin() returns a reverse_iterator pointing to the last element of set. Whereas, set::rend() returns a reverse_iterator pointing to element before the first element.
Now to iterate a set in reverse direction, we need to create an reverse_iterator and initialise it with set::rbegin(). So that it points to the last element of set and then we will keep on access and increment the iterator to next till set::rend() is reached i.e. beginning of set.
1
2
3
4
5
6
7
8
9
10
11
// Creating a reverse iterator pointing to end of set i.e. rbegin